import Vue from 'vue';

import { $dayjs } from '@/main.js';
export function useVModel(obj, emit = 'input') {
	let _this = this;
	obj ??= _this.value;
	if (typeof obj !== 'object') {
		return obj;
	}
	return new Proxy(obj, {
		get(target, propKey, receiver) {
			return Reflect.get(target, propKey, receiver);
		},
		set(target, propKey, value, receiver) {
			_this.$emit(emit, {
				...target,
				[propKey]: value,
			});

			return Reflect.set(target, propKey, value, receiver);
		},
	});
}

export function A_formatTime(time, reg = 0) {
	if (!time || time == 0 || time == '0') return '';
	switch (reg) {
		case 0:
		case '0':
			reg = 'YYYY-MM-DD';
			break;
		case 1:
		case '1':
			reg = 'YYYY-MM-DD HH:mm:ss';
			break;
	}
	let pass = $dayjs(time)?.isValid?.();
	if (!pass) return time;

	return $dayjs(time).format(reg);
}

export function refRedirect(ref) {
	for (const key in this.$refs[ref]) {
		if (Object.hasOwnProperty.call(this.$refs[ref], key)) {
			let element = this.$refs[ref][key];
			let reg = /(\_|\$)/g;
			if (
				!reg.test(key) &&
				Object.prototype.toString.call(element) === '[object Function]'
			) {
				this[`${ref}_${key}`] = element;
			}
		}
	}
}
export function notEmpty(value) {
	let result = true;
	if (value === undefined || value === null || value === '') {
		result = false;
	} else {
		result = true;
	}
	if (Object.prototype.toString.call(value) === '[object Array]') {
		if (value.length == 0) {
			result = false;
		} else {
			result = true;
		}
	}
	if (Object.prototype.toString.call(value) === '[object Object]') {
		if (Object.keys(value).length == 0) {
			result = false;
		} else {
			result = true;
		}
	}
	return result;
}
export function Empty(value) {
	let result = true;
	if (value === undefined || value === null || value === '') {
		result = true;
	} else {
		result = false;
	}
	if (Object.prototype.toString.call(value) === '[object Array]') {
		if (value.length == 0) {
			result = true;
		} else {
			result = false;
		}
	}
	if (Object.prototype.toString.call(value) === '[object Object]') {
		if (Object.keys(value).length == 0) {
			result = true;
		} else {
			result = false;
		}
	}
	return result;
}
export function scrollToError(ref) {
	let error = document.querySelector('.el-form-item.is-error');
	let parentNodeClass = error?.parentElement?.className;
	let options = {
		behavior: 'smooth',
		block: 'center',
		inline: 'center',
	};
	if (parentNodeClass === 'cell') {
		options.behavior = 'auto';
	}
	error?.scrollIntoView(options);
}

export function checkNumberInput(value, callback) {
	let match = value.match(/^(0|([1-9]\d*))(\.\d{0,2})?$/);
	if (match) {
		callback(match[0]); // 如果匹配，返回匹配结果
	} else {
		if (value.startsWith('0') && value[1] !== '.') {
			callback(value.slice(1)); // 处理以0开头但后面不跟小数点的情况
		} else {
			callback(value.slice(0, -1)); // 不匹配，删除最后一个字符
		}
	}
}

export function checkListNumberInput(value) {
	let match = value.match(/^(0|([1-9]\d*))(\.\d{0,2})?$/);
	if (match) {
		return match[0]; // 如果匹配，返回匹配结果
	} else {
		if (value.startsWith('0') && value[1] !== '.') {
			return value.slice(1); // 处理以0开头但后面不跟小数点的情况
		} else {
			return value.slice(0, -1); // 不匹配，删除最后一个字符
		}
	}
}
export function format_thousand(number) {
	if (Empty(number)) return '-';
	let price = number * 1;
	if (!Number.isFinite(price)) return '-';
	let fixed2 = price.toFixed(2);
	return !(fixed2 + '').includes('.') // 就是说1-3位后面一定要匹配3位
		? (fixed2 + '').replace(/\d{1,3}(?=(\d{3})+$)/g, match => {
				return match + ',';
		  })
		: (fixed2 + '').replace(/\d{1,3}(?=(\d{3})+(\.))/g, match => {
				return match + ',';
		  });
	// return new Intl.NumberFormat("en-us").format(fixed2);
}

export function checkEmptyString(value) {
	if (value == null || value == undefined || value == '') {
		return '/';
	} else {
		return value;
	}
}
// 数组对象遍历  值为空返回"-"
export function processArray(arr) {
	return arr.map(item => {
		for (let key in item) {
			if (item.hasOwnProperty(key)) {
				if (
					item[key] === null ||
					item[key] === undefined ||
					item[key] === ''
				) {
					item[key] = '--';
				}
			}
		}
		return item;
	});
}

function _basePath(path) {
	if (Empty(path)) {
		return '';
	}
	// 若是数组，则直接返回
	if (Array.isArray(path)) return path;
	// 若有 '[',']'，则替换成将 '[' 替换成 '.',去掉 ']'
	return path.replace(/\[/g, '.').replace(/\]/g, '').split('.');
}
export const A_realName = (name, data = {}) => {
	const base_name = _basePath(name);
	if (
		typeof base_name === 'object' &&
		Array.isArray(base_name) &&
		base_name.length > 1
	) {
		const realname = base_name.reduce(
			(a, b) => (a += `#${b}`),
			'_formdata_',
		);
		return realname;
	}
	return base_name[0] || name;
};

export const A_review = ({ value, dict = {}, showErrorValue = true }) => {
	if (!notEmpty(value)) return '-';
	if ('list' in dict && dict?.list?.length > 0) {
		let values = '';
		if (Object.prototype.toString.call(value) == '[object Array]') {
			values = value;
		} else if (value?.includes?.(',')) {
			values = value?.toString?.().split(',');
		} else {
			values = [value?.toString?.()];
		}

		let word = undefined;
		let arr = [];
		if (Object.prototype.toString.call(dict.list) == '[object Function]') {
			arr = dict.list();
		}
		if (Object.prototype.toString.call(dict.list) == '[object Array]') {
			arr = dict.list;
		}
		if (arr?.length > 0) {
			word = arr.reduce((prev, next) => {
				let nextLabel = '';
				if (
					typeof next === 'object' &&
					values.includes(
						next[dict.key] ?? next?.value ?? next?.dictValue,
					)
				) {
					nextLabel =
						next[dict.label] ??
						next?.text ??
						next?.label ??
						next?.dictLabel;
				} else if (
					(typeof next === 'number' || typeof next === 'string') &&
					values.includes(next)
				) {
					nextLabel = next;
				}
				return `${prev ? prev : ''}${
					prev && nextLabel ? '，' : ''
				}${nextLabel}`;
			}, word);
		}

		if (showErrorValue === true) {
			return word ?? value ?? '-';
		} else {
			return word ?? '-';
		}
	} else {
		return value;
	}
};

export const A_viewPrice = val => {
	if (Empty(val)) return '-';
	let price = Number(val);
	if (isNaN(price)) return '-';
	// if (Empty(val) || !Number.isFinite(price)) return '-';
	let fixed2 = price.toFixed(2);
	return !(fixed2 + '').includes('.') // 就是说1-3位后面一定要匹配3位
		? (fixed2 + '').replace(/\d{1,3}(?=(\d{3})+$)/g, match => {
				return match + ',';
		  })
		: (fixed2 + '').replace(/\d{1,3}(?=(\d{3})+(\.))/g, match => {
				return match + ',';
		  });
};
export const A_deepClone = (source, cache) => {
	if (!cache) {
		cache = new Map();
	}
	if (source instanceof Object) {
		// 不考虑跨 iframe
		if (cache.get(source)) {
			return cache.get(source);
		}
		let result;
		if (source instanceof Function) {
			if (source.prototype) {
				// 有 prototype 就是普通函数
				result = function () {
					return source.apply(this, arguments);
				};
			} else {
				result = (...args) => {
					return source.call(undefined, ...args);
				};
			}
		} else if (source instanceof Array) {
			result = [];
		} else if (source instanceof Date) {
			result = new Date(source - 0);
		} else if (source instanceof RegExp) {
			result = new RegExp(source.source, source.flags);
		} else {
			result = {};
		}
		cache.set(source, result);
		for (let key in source) {
			if (source.hasOwnProperty(key)) {
				result[key] = A_deepClone(source[key], cache);
			}
		}
		return result;
	} else {
		return source;
	}
};
